package com.cy;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

//定义配置类，设计流控返回值
@Configuration
public class GatewayConfig网关流控返回标准 {
    public GatewayConfig网关流控返回标准() {
        //GatewayCallbackManager--底层将流控返回值返回给客户端的一个类
        //直接在里面--new BlockRequestHandler(){}
        GatewayCallbackManager.setBlockHandler(new BlockRequestHandler() {
            //当我i们请求的url被限流了,可以直接执行此方法,在此方法中我们进行限流响应数据的设计
            //此方法的返回值可以响应到客户端
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
                Map<String, Object> map = new HashMap<>();
                map.put("state", 0);
                map.put("message", "请求次数太多，请稍后再试");
                try {
                    String str = new ObjectMapper().writeValueAsString(map);
                    //返回值,如何构建基于方法返回值类型--要参考源码
                    //ServerResponse--Mono的响应类型,ok()--成功码,body()--ServerResponse底层的方法,返回类型是Mono
                    return ServerResponse.ok().body(Mono.just(str), String.class);
                } catch (Exception e) {
                    e.printStackTrace(); //控制台打印异常
                    throw new RuntimeException(e.getMessage());//抛出异常
                }
            }
        });
    }
}
